<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <!-- import CSS -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/element-ui/2.15.9/theme-chalk/index.css">
</head>
<body>
<div id="app">
    <input type="text" placeholder="说点啥吧......" v-model="weibo.content">

    <!--action:设置文件上传的地址
    name：设置参数名称
    limit:设置上传文件的数量
    :on-success，成功上传事件
   :on-remove，删除事件 -->
    <el-upload
            action="/upload"
            name="picFile"
            limit="1"
            list-type="picture-card"
            :on-success="handleSuccess"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
        <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

    <el-button @click="insert()">发布微博</el-button>
</div>
</body>
<!-- import Vue before Element -->
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.14/vue.js"></script>
<!-- import JavaScript -->
<script src="https://cdn.staticfile.org/element-ui/2.15.9/index.min.js"></script>
<script>
   let v =  new Vue({
        el: '#app',
        data: function() {
            return {
                dialogImageUrl: '',
                dialogVisible: false,
                weibo:{content:"",url:""}
            }
        },
       methods:{
            insert(){
                if(v.weibo.url==""){
                    alert("请上传图片");
                    return;
                }
                //发起新增微博的post异步请求
                axios.post("/insert",v.weibo).then(function () {
                    location.href = "/";//返回首页
                })
            },
           handleSuccess(response,file,fileList){
               //此方法是上传组件成功上传文件后调用的方法，response就是后端响应数据
               //file代表当前上传完成的文件对象
               //fileList代表上传完成的所有文件对象
               //上传成功后把服务器响应的图片路径赋值给微博对象
               v.weibo.url = response;
           },
           handleRemove(file, fileList) {
                //因为图片被删除了，所以weibo对象里面的图片路径url应该被清空
                v.weibo.url = "";
               //发出异步删除请求
               axios.post("/remove?url="+file.response).then(function () {
                   console.log("删除成功");
               })
           },
           handlePictureCardPreview(file) {
               this.dialogImageUrl = file.url;
               this.dialogVisible = true;
           }
       }
    })
</script>
</html>